<template>
  <div class="invoice-list-container">
    <div class="page-header">
      <h2 class="page-title">发票管理</h2>
      <el-button class="create-button" type="primary" @click="createInvoice">
        <el-icon>
          <Plus/>
        </el-icon>
        新增发票
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form" inline @keyup.enter="handleSearch">
        <el-form-item label="发票号码">
          <el-input v-model="searchForm.invoiceNumber" clearable placeholder="请输入发票号码"></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" clearable placeholder="请输入供应商名称"></el-input>
        </el-form-item>
        <el-form-item label="发票分类">
          <el-select v-model="searchForm.category" clearable placeholder="请选择分类" style="min-width: 200px">
            <el-option label="增值税专用发票" value="增值税专用发票"></el-option>
            <el-option label="增值税普通发票" value="增值税普通发票"></el-option>
            <el-option label="增值税电子普通发票" value="增值税电子普通发票"></el-option>
            <el-option label="增值税电子专用发票" value="增值税电子专用发票"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
              v-model="searchForm.dateRange"
              :shortcuts="dateShortcuts"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon>
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-operations">
        <el-button :disabled="selectedItems.length === 0" type="danger" @click="handleDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon>
            <Download/>
          </el-icon>
          导出全部
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
          v-loading="loading"
          :data="dataSource"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="发票号码" min-width="180" prop="invoiceNumber" show-overflow-tooltip></el-table-column>
        <el-table-column label="发票类型" min-width="180" prop="category" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip :content="scope.row.category" effect="light" placement="top">
              <span>{{ scope.row.category }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="200" prop="supplierName" show-overflow-tooltip></el-table-column>
        <el-table-column label="金额（含税）" prop="totalAmountWithTax" width="150">
          <template #default="scope">
            <span class="amount">{{ formatCurrency(scope.row.totalAmountWithTax) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="税额" prop="totalTax" width="150">
          <template #default="scope">
            <span class="tax-amount">{{ formatCurrency(scope.row.totalTax) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开票日期" prop="issueDate" width="120"></el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <div class="action-buttons">
              <div class="action-row">
                <el-button size="small" type="primary" @click="handleView(scope.row.id)">查看</el-button>
                <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
              </div>
              <div class="action-row">
                <el-button size="small" type="primary" @click="matchInvoice(scope.row)">匹配</el-button>
                <el-popconfirm
                    title="确定删除此发票吗？此操作不可撤销。"
                    @confirm="handleDeleteInvoice(scope.row.id)"
                >
                  <template #reference>
                    <el-button size="small" type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="pagination-total">共 {{ pagination.total }} 条</span>
        <el-select v-model="pagination.pageSize" class="pagination-select" @change="handleSizeChange">
          <el-option v-for="item in [10, 20, 50, 100]" :key="item" :label="`${item}条/页`" :value="item"/>
        </el-select>
        <el-pagination
            v-model:current-page="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            background
            layout="prev, pager, next, jumper"
            @current-change="handleTableChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Download, Plus, Refresh, Search} from '@element-plus/icons-vue';
import {
  batchDeleteInvoice,
  deleteInvoice,
  exportInvoice,
  findInvoiceByCondition,
  findInvoiceByNumber,
  getInvoiceByDateRange,
  getInvoiceList
} from '../../api/invoice';

const router = useRouter();

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    }
  }
];

// 列表相关数据
const loading = ref(true);
const dataSource = ref<any[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 查询条件
const searchForm = reactive({
  invoiceNumber: '',
  supplierName: '',
  category: undefined as string | undefined,
  dateRange: [] as string[],
});

// 处理API响应数据（提取为复用函数）
const processApiResponse = (data: any[], total: number | null = null) => {
  if (!data) {
    dataSource.value = [];
    pagination.total = 0;
    return;
  }

  let processedData = Array.isArray(data) ? data : [];
  pagination.total = total || processedData.length;

  // 处理数据：确保每条记录都有价税合计
  processedData.forEach(item => {
    // 如果价税合计为0或不存在，尝试计算
    if (!item.totalAmountWithTax) {
      const calculatedTotal = calculateTotalWithTax(item);
      if (calculatedTotal > 0) {
        item.totalAmountWithTax = calculatedTotal;
      }
    }
  });

  dataSource.value = processedData;
};

// 匹配发票
const matchInvoice = (row: any) => {
  router.push(`/dashboard/three-way-match?invoiceId=${row.id}`);
};

// 获取发票列表数据
const fetchInvoiceList = async () => {
  loading.value = true;
  try {
    // 如果有任何搜索条件，使用搜索接口
    if (hasSearchConditions()) {
      await fetchWithSearchConditions();
    } else {
      // 没有搜索条件，获取所有发票
      await fetchAllInvoices();
    }
  } catch (error) {
    dataSource.value = [];
    pagination.total = 0;
    ElMessage.error('获取发票列表失败，请检查网络连接和后端服务');
  } finally {
    loading.value = false;
  }
};

// 检查是否有搜索条件
const hasSearchConditions = () => {
  return (searchForm.invoiceNumber && searchForm.invoiceNumber.trim() !== '') ||
      (searchForm.supplierName && searchForm.supplierName.trim() !== '') ||
      searchForm.category !== undefined ||
      (searchForm.dateRange && searchForm.dateRange.length === 2);
};

// 获取所有发票
const fetchAllInvoices = async () => {
  loading.value = true;
  try {
    // 使用基本列表接口获取所有发票
    const response = await getInvoiceList({
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    });

    // 处理后端返回的数据
    if (response && response.code === 200 && response.data) {
      // 标准API响应格式
      if (response.data.records && Array.isArray(response.data.records)) {
        processApiResponse(response.data.records, response.data.total);
      } else if (Array.isArray(response.data)) {
        // 如果直接是数组，需要手动进行分页处理
        const total = response.data.length;
        // 每次只显示pageSize条数据
        const start = (pagination.current - 1) * pagination.pageSize;
        const end = start + pagination.pageSize;
        const pagedData = response.data.slice(start, end);
        processApiResponse(pagedData, total);
      }
    } else if (response && response.success && response.data) {
      // 另一种API响应格式
      if (response.data.records && Array.isArray(response.data.records)) {
        processApiResponse(response.data.records, response.data.total);
      } else if (Array.isArray(response.data)) {
        // 手动处理分页
        const total = response.data.length;
        const start = (pagination.current - 1) * pagination.pageSize;
        const end = start + pagination.pageSize;
        const pagedData = response.data.slice(start, end);
        processApiResponse(pagedData, total);
      }
    } else if (Array.isArray(response)) {
      // 如果后端直接返回数组，需要手动分页
      const total = response.length;
      const start = (pagination.current - 1) * pagination.pageSize;
      const end = start + pagination.pageSize;
      const pagedData = response.slice(start, end);
      processApiResponse(pagedData, total);
    } else {
      // 处理其他可能的响应格式
      let extractedData: any[] = [];
      let totalItems = 0;

      if (response && typeof response === 'object') {
        // 尝试从各种可能的数据结构中提取数据
        if (response.data && Array.isArray(response.data)) {
          extractedData = response.data;
          totalItems = extractedData.length;
        } else if (response.records && Array.isArray(response.records)) {
          extractedData = response.records;
          totalItems = response.total || extractedData.length;
        } else if (response.content && Array.isArray(response.content)) {
          extractedData = response.content;
          totalItems = response.totalElements || extractedData.length;
        }
      }

      if (extractedData.length > 0) {
        processApiResponse(extractedData, totalItems);
      } else {
        dataSource.value = [];
        pagination.total = 0;
        ElMessage.warning('暂无发票数据，请创建新发票');
      }
    }
  } catch (error: any) {
    console.error('获取所有发票列表失败:', error);
    console.error('错误类型:', error.name);
    console.error('错误消息:', error.message);

    // 如果请求被取消，不显示错误消息
    if (error.name === 'CanceledError') {
      return;
    }

    if (error.code && error.message) {
      console.error('错误状态码:', error.code);
      console.error('错误描述:', error.message);
    }

    if (error.response) {
      console.error('HTTP状态码:', error.response.status);
      console.error('响应数据:', error.response.data);
    }

    dataSource.value = [];
    pagination.total = 0;
    ElMessage.error({
      message: `获取发票列表失败: ${error.message || '服务器内部错误'}`,
      duration: 5000
    });
  } finally {
    loading.value = false;
  }
};

// 根据发票号码搜索
const fetchByInvoiceNumber = async () => {
  try {
    // 使用专门的发票号码查询API
    const response = await findInvoiceByNumber(searchForm.invoiceNumber.trim());

    if (response && response.code === 200 && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (response && response.success && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (Array.isArray(response)) {
      processApiResponse(response);
    } else if (response && response.data && Array.isArray(response.data)) {
      processApiResponse(response.data);
    } else {
      console.warn('发票号码查询返回格式异常:', response);
      dataSource.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('发票号码查询失败:', error);
    throw error;
  }
};

// 多条件查询
const fetchWithMultipleConditions = async () => {
  try {
    // 构建搜索实体
    const searchInvoice = buildSearchInvoice();

    // 使用条件查询API
    const response = await findInvoiceByCondition(searchInvoice);

    if (response && response.code === 200 && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (response && response.success && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (Array.isArray(response)) {
      processApiResponse(response);
    } else if (response && response.data && Array.isArray(response.data)) {
      processApiResponse(response.data);
    } else {
      console.warn('多条件查询返回格式异常:', response);
      dataSource.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('多条件查询失败:', error);
    throw error;
  }
};

// 带搜索条件获取发票
const fetchWithSearchConditions = async () => {
  // 如果只有日期范围条件
  if (onlyHasDateRangeCondition()) {
    await fetchInvoiceListByDateRange();
    return;
  }

  // 如果主要是按发票号码搜索且没有其他条件
  if (searchForm.invoiceNumber && searchForm.invoiceNumber.trim() !== '' &&
      !searchForm.category && !searchForm.dateRange) {
    await fetchByInvoiceNumber();
    return;
  }

  // 其他复合条件，使用多条件查询
  await fetchWithMultipleConditions();
};

// 构建查询参数
const buildSearchParams = (params: any) => {
  // 添加发票号码查询条件（如果有）
  if (searchForm.invoiceNumber && searchForm.invoiceNumber.trim()) {
    params.invoiceNumber = searchForm.invoiceNumber.trim();
  }

  // 添加发票类别查询条件（如果有）
  if (searchForm.category) {
    params.category = searchForm.category;
  }

  // 添加日期范围查询条件（如果有）
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.startDate = searchForm.dateRange[0];
    params.endDate = searchForm.dateRange[1];
  }

  return params;
};

// 判断是否只有日期范围条件
const onlyHasDateRangeCondition = () => {
  return searchForm.dateRange &&
      searchForm.dateRange.length === 2 &&
      !searchForm.invoiceNumber &&
      !searchForm.category;
};

// 构建搜索实体对象
const buildSearchInvoice = () => {
  const searchInvoice: Record<string, any> = {};

  if (searchForm.invoiceNumber && searchForm.invoiceNumber.trim()) {
    searchInvoice.invoiceNumber = searchForm.invoiceNumber.trim();
  }

  if (searchForm.supplierName && searchForm.supplierName.trim()) {
    searchInvoice.supplierName = searchForm.supplierName.trim();
  }

  if (searchForm.category) {
    searchInvoice.category = searchForm.category;
  }

  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    searchInvoice.startDate = searchForm.dateRange[0];
    searchInvoice.endDate = searchForm.dateRange[1];
  }

  return searchInvoice;
};

// 查询按钮点击事件
const handleSearch = () => {
  // 重置到第一页
  pagination.current = 1;

  // 检查搜索条件是否有效
  const hasSearchCriteria = hasSearchConditions();

  if (!hasSearchCriteria) {
    ElMessage({
      message: '请至少输入一个搜索条件',
      type: 'warning'
    });
    return;
  }

  // 执行搜索
  fetchInvoiceList();
};

// 重置查询条件
const resetSearch = () => {
  clearAllSearchConditions();
  pagination.current = 1;

  // 重置后加载所有发票
  fetchAllInvoices();
};

// 处理行点击
const handleRowClick = (row: any) => {
  router.push(`/dashboard/invoice-detail/${row.id}`);
};

// 查看发票
const handleView = (id: string) => {
  router.push(`/dashboard/invoice-detail/${id}`);
};

// 编辑发票
const handleEdit = (id: string) => {
  router.push(`/dashboard/invoice-edit/${id}`);
};

// 新增发票
const createInvoice = () => {
  router.push('/dashboard/invoice-add');
};

// 删除发票
const handleDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(
      '确定要删除选中的发票吗？此操作不可撤销。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      loading.value = true;
      const ids = selectedItems.value.map(item => item.id);
      await batchDeleteInvoice(ids);
      ElMessage.success('批量删除成功');
      fetchInvoiceList(); // 重新加载数据
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败，请重试');
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 获取发票类型文本
const getCategoryText = (category: string) => {
  if (!category) return '';

  const categoryMap: Record<string, string> = {
    '增值税专用发票': '增值税专用发票',
    '增值税普通发票': '增值税普通发票',
    '增值税电子发票': '增值税电子发票',
    '收据': '收据',
    '其他': '其他'
  };

  return categoryMap[category] || category;
};

// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0.00';
  return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 计算发票的价税合计
const calculateTotalWithTax = (item: any) => {
  if (item.totalAmountWithTax !== undefined && item.totalAmountWithTax !== null) {
    return item.totalAmountWithTax;
  }

  // 如果明细不存在，无法计算
  if (!item.details || !Array.isArray(item.details) || item.details.length === 0) {
    return 0;
  }

  // 从明细中计算
  const total = item.details.reduce((sum: number, detail: any) => {
    const amount = parseFloat(detail.amount || 0);
    const tax = parseFloat(detail.taxAmount || 0);
    return sum + amount + tax;
  }, 0);

  const calculatedTotal = parseFloat(total.toFixed(2));
  // 已计算的结果缓存在对象上，避免重复计算
  item.totalAmountWithTax = calculatedTotal;
  return calculatedTotal;
};

// 格式化公司信息
const formatCompanyInfo = (info: string) => {
  if (!info) return '-';
  return info;
};

// 根据日期范围查询发票列表
const fetchInvoiceListByDateRange = async () => {
  if (!searchForm.dateRange || searchForm.dateRange.length !== 2) {
    ElMessage.warning('请选择日期范围');
    return;
  }

  try {
    // 确保日期格式正确 - 后端可能需要特定的日期格式
    const startDate = typeof searchForm.dateRange[0] === 'string'
        ? searchForm.dateRange[0]
        : new Date(searchForm.dateRange[0]).toISOString().split('T')[0];

    const endDate = typeof searchForm.dateRange[1] === 'string'
        ? searchForm.dateRange[1]
        : new Date(searchForm.dateRange[1]).toISOString().split('T')[0];

    // 调用日期范围查询API
    const response = await getInvoiceByDateRange(startDate, endDate);

    if (response && response.code === 200 && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (response && response.success && response.data) {
      processApiResponse(Array.isArray(response.data) ? response.data : [response.data]);
    } else if (Array.isArray(response)) {
      processApiResponse(response);
    } else if (response && response.data && Array.isArray(response.data)) {
      processApiResponse(response.data);
    } else {
      console.warn('日期范围查询返回格式异常:', response);
      dataSource.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('日期范围查询失败:', error);
    ElMessage.error('根据日期范围查询发票失败');
    throw error;
  }
};

// 清空所有搜索条件
const clearAllSearchConditions = () => {
  searchForm.invoiceNumber = '';
  searchForm.category = undefined;
  searchForm.dateRange = [];
};

// 表格分页变化事件
const handleTableChange = (val: number) => {
  // 区分是页码变化还是每页条数变化
  if (typeof val === 'number') {
    pagination.current = val;
  }

  // 重新加载数据
  fetchInvoiceList();
};

// 每页条数变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.current = 1; // 切换每页条数时重置为第一页

  // 重新加载数据
  fetchInvoiceList();
};

// 组件挂载时获取发票列表
onMounted(async () => {
  try {
    loading.value = true;
    // 初始化时获取所有发票
    await fetchAllInvoices();
  } catch (error) {
    console.error('初始加载发票列表失败:', error);
    ElMessage.error('获取发票列表失败，请检查网络连接和后端服务');
  } finally {
    loading.value = false;
  }
});

// 格式化金额为货币格式
const formatCurrency = (value: number) => {
  if (!value && value !== 0) return '';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2
  }).format(value);
};

// 是否有选中项
const hasSelection = ref(false);
// 选中的项目
const selectedItems = ref<any[]>([]);

// 选中项变化
const handleSelectionChange = (selection: any[]) => {
  selectedItems.value = selection;
  hasSelection.value = selection.length > 0;
};

// 导出全部
const handleExport = async () => {
  try {
    // 先检查是否已经在执行导出操作
    if (loading.value) {
      ElMessage.warning('导出操作正在进行中，请勿重复点击');
      return;
    }

    loading.value = true;
    ElMessage.info('正在准备导出数据，请稍候...');

    // 检查token是否存在
    const token = sessionStorage.getItem('token');
    if (!token) {
      ElMessage.error('您未登录或登录已过期，请先登录系统');
      router.push('/login');
      return;
    }

    // 构建导出参数，包含当前的搜索条件
    const exportParams: any = {};

    // 添加发票号码查询条件（如果有）
    if (searchForm.invoiceNumber && searchForm.invoiceNumber.trim()) {
      exportParams.invoiceNumber = searchForm.invoiceNumber.trim();
    }

    // 添加供应商查询条件（如果有）
    if (searchForm.supplierName && searchForm.supplierName.trim()) {
      exportParams.supplierName = searchForm.supplierName.trim();
    }

    // 添加发票类别查询条件（如果有）
    if (searchForm.category) {
      exportParams.category = searchForm.category;
    }

    // 添加日期范围查询条件（如果有）
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      exportParams.startDate = searchForm.dateRange[0];
      exportParams.endDate = searchForm.dateRange[1];
    }

    // 调用导出API
    const response = await exportInvoice(exportParams);

    // 检查响应状态
    if (!response.success) {
      ElMessage.error(`导出失败: ${response.message}`);
      console.error('导出失败:', response);
      return;
    }

    // 处理文件下载
    if (response.data instanceof Blob) {
      // 检查Blob类型，确保是Excel文件
      if (response.data.type.includes('spreadsheetml') ||
          response.data.type === 'application/octet-stream' ||
          response.data.type === 'application/vnd.ms-excel') {
        // 创建下载链接
        const blob = response.data;
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `发票列表_${new Date().getTime()}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        ElMessage.success('导出成功');
      } else {
        // 如果不是Excel，可能是错误消息
        const reader = new FileReader();
        reader.onload = () => {
          try {
            // 尝试解析为JSON
            const result = JSON.parse(reader.result as string);
            console.error('导出返回错误JSON:', result);
            ElMessage.error(`导出失败: ${result.message || '未知错误'}`);
          } catch (e) {
            // 不是JSON，显示通用错误
            console.error('导出返回未知格式:', reader.result);
            ElMessage.error('导出失败，返回格式不正确');
          }
        };
        reader.onerror = (e) => {
          console.error('读取Blob内容失败:', e);
          ElMessage.error('导出失败，无法读取响应内容');
        };
        reader.readAsText(response.data);
      }
    } else {
      console.error('导出响应不是Blob类型:', typeof response.data);
      ElMessage.error('导出失败，响应格式不正确');
    }
  } catch (error: any) {
    console.error('导出失败:', error);
    // 特别处理401错误，避免重复显示错误信息和无限循环
    if (error.code === 401) {
      ElMessage.error('导出失败: 登录已过期，请重新登录');
      // 不再自动跳转到登录页面，避免循环
    } else {
      ElMessage.error(`导出失败: ${error.message || '请稍后重试'}`);
    }
  } finally {
    loading.value = false;
  }
};

// 单个删除
const handleDeleteInvoice = async (id: string) => {
  try {
    await deleteInvoice(id);
    ElMessage.success('删除成功');
    fetchInvoiceList();
  } catch (error) {
    console.error('删除发票失败:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
};
</script>

<style scoped>
.invoice-list-container {
  padding: 20px;
  background-color: #ffffff;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.create-button {
  background-color: #1890FF;
  border-color: #1890FF;
  transition: all 0.3s;
}

.create-button:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: none;
  border: 1px solid #ebeef5;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  border-radius: 4px;
  box-shadow: none;
  border: 1px solid #ebeef5;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #F56C6C !important;
  border-color: #F56C6C !important;
}

:deep(.el-button--success) {
  background-color: #67C23A !important;
  border-color: #67C23A !important;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
}

:deep(.el-button--danger:disabled) {
  background-color: #fab6b6 !important;
  border-color: #fab6b6 !important;
  color: white !important;
}

.data-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-row {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.btn-action {
  padding: 5px 12px;
  font-size: 12px;
  border-radius: 4px;
  min-width: 52px; /* 保证按钮宽度一致 */
}

.btn-view {
  background-color: #1890FF;
  color: white;
  border-color: #1890FF;
}

.btn-edit {
  background-color: #67C23A;
  color: white;
  border-color: #67C23A;
}

.btn-match {
  background-color: #E6A23C;
  color: white;
  border-color: #E6A23C;
}

.btn-delete {
  background-color: #F56C6C;
  color: white;
  border-color: #F56C6C;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  white-space: nowrap;
}

.status-new {
  background-color: #e8f4ff;
  color: #1890FF;
}

.status-matched {
  background-color: #f0f9eb;
  color: #67C23A;
}

.status-diff {
  background-color: #fdf6ec;
  color: #E6A23C;
}

.amount, .tax-amount {
  color: #F56C6C;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  background-color: #fafafa;
  padding: 10px;
  border-radius: 4px;
}

.pagination-total {
  margin-right: 15px;
  color: #606266;
}

.pagination-select {
  margin-right: 15px;
  width: 100px;
}

:deep(.el-card__body) {
  padding: 15px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #1890FF;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa !important;
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .invoice-list-container {
    padding: 10px;
  }

  .table-operations {
    flex-direction: column;
    gap: 5px;
  }

  .action-buttons {
    gap: 3px;
  }

  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }

  .pagination-select, .pagination-total {
    margin-right: 0;
  }
}

/* 改进下拉框和表格单元格样式 */
:deep(.el-select-dropdown__item) {
  white-space: normal;
  height: auto;
  line-height: 1.5;
  padding: 8px 12px;
}

:deep(.el-table .cell) {
  white-space: normal;
  word-break: break-word;
  line-height: 1.5;
}
</style>